package rs.frenjoynet.core.initialiser;

import rs.frenjoynet.core.core.BaseFacade;

import javax.servlet.ServletContextListener;
import javax.servlet.ServletContextEvent;
import javax.naming.NamingException;
import javax.naming.InitialContext;
import java.util.List;
import java.util.ArrayList;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


/**
 * Created by IntelliJ IDEA.
 * User: ppopovic
 * Date: 02.10.2009.
 * Time: 13.40.06
 * To change this template use File | Settings | File Templates.
 */
public class CoreInitializer implements ServletContextListener
{
   private Log log = LogFactory.getLog(CoreInitializer.class);
	protected final List<String> ejbLoadOrderList = new ArrayList<String>();

	protected void makeOrder()
	{

		ejbLoadOrderList.add("java:comp/env/myEjb/BaseFacadeImpl");
		ejbLoadOrderList.add("java:comp/env/ejb/CoreSecurityFacadeBean");
//		ejbLoadOrderList.add("java:comp/env/ejb/CoreRefBookFacadeBean");
		ejbLoadOrderList.add("java:comp/env/ejb/CoreApplicationsFacadeBean");
	}


	public void contextInitialized(ServletContextEvent sce)
	{
		makeOrder();

		initOrderedEJBs();

		initOtherEJBs();
	}

	protected void initOtherEJBs()
	{
		// TODO Videtri kao je cika Aleksey Uradiooo- ja ovde nista pametno nisam imao
	}

	protected void initOrderedEJBs()
	{
		for (String name : ejbLoadOrderList)
		{
			BaseFacade facade = getFacade(name);
			if (facade != null)
			{
				facade.initialize();
				log.info(facade.getClass() + "  initialized!");
			}
		}
	}

//	protected BaseFacade getFacade(String facadeName)
//	{
//		BaseFacade facade = null;
//		try
//		{
//			InitialContext context = new InitialContext();
//			facade = (BaseFacade)context.lookup(facadeName);
//		}
//		catch (NamingException e)
//		{
//			log.error(e);
//		}
//
//		return facade;
//	}


	public void contextDestroyed(ServletContextEvent sce)
	{
	}

	protected BaseFacade getFacade(String facadeName)
	{
		BaseFacade facade = null;
		try
		{
			InitialContext context = new InitialContext();
			facade = (BaseFacade)context.lookup(facadeName);
		}
		catch (NamingException e)
		{
			log.error(e);
		}

		return facade;
	}

}

